<template>
  <div class="mention-box">
    <div class="mention-editor" ref="editor"></div>
    <div class="mention-btn" @click="handlerSend">
      <slot name="submit">
        提交
      </slot>
    </div>
  </div>
</template>

<script setup >
import { onMounted } from 'vue'
import Quill from "quill";
import mention from "quill-mention";
import "quill-mention/dist/quill.mention.min.css";
import {regHttp, getRegExp} from './utils/'

const props = defineProps({
  placeholder: {
    type: String,
    default: '请输入内容'
  },
  allowedChars: {
    type: RegExp,
    default: /^[\u4e00-\u9fa5]*$/
  },
  renderItem: {
    type: Function,
    default: (item, search) => item.value
  },
  dataSource: {
    type: Function,
    default: (searchTerm, mentionChar) => []
  }
})

const emit = defineEmits(['done'])

const editor = ref(null);

const initQuill = () => {
  new Quill(editor.value, {
    placeholder: props.placeholder,
    modules: {
      mention: {
        allowedChars: props.allowedChars,
        mentionDenotationChars: ["@"],
        positionStrategy: "fixed",
        // 人员框渲染
        renderItem: (data, search) => {
          return props.renderItem(data, search)
        },
        renderLoading: () => {
          return 'loading...'
        },
        source: async (searchTerm, renderList, mentionChar) => {
          const list = await props.dataSource(searchTerm, mentionChar)
          renderList(list, searchTerm);
        }
      }
    }
  })
}

const handlerSend = () => {
  const atUsers = getAts();
  const content = editor.value.innerHTML
    .replace("ql-editor", "")
    .replace("contenteditable", "a")
    .replace(regHttp, function (item) {
      // 这里识别了链接
      return "<a href='" + item + "' target='_blank'>" + item + "</a>";
    });
  const contentText = getContentText();
  if (contentText == "\n") {
    return;
  }


  emit('done', {
    contentText,
    content,
    atUsers
  })

  clear()
}

const getAts = () => {
  let domStr = editor.value.outerHTML;
  let patt = /<span[^>]+data-id=['"]([^'"]+)['"]+/g;
  let result = [],
    temp;
  
  while ((temp = patt.exec(domStr)) != null) {
    result.push({ userId: temp[1]});
  }
  return result;
}

const getContentText = () => {
  const text = editor.value.innerText;
  return text;
}
const clear = () => {
  const element = document.getElementsByClassName("ql-editor")[0];
  element.textContent = "";
}


onMounted(() => {
  initQuill()
})

</script>

<style lang="scss" >
@import "./style/quill.snow.css";
@import "./style/vueat.scss";
</style>